import { observable, action, computed, toJS } from 'mobx';
import loadjs from 'loadjs';
import { message } from 'antd';
import { WeaTools, WeaInputLocale } from 'ecCom';

const { ua } = WeaTools;
const getCurrentLabel = WeaInputLocale.getCurrentLabel;
const getMultiStrFromBase64 = WeaInputLocale.getMultiStrFromBase64;
import * as LOGIN_API from '../apis/login';
import { doEvent } from '../util/eventUtil';
import { ecComFiles, comMobxFiles, portalPublicFiles } from '../constants/files';
import { getCookieValue, getLSValue, setLSValue, initLSValue } from '../util/loginUtil';

export default class LoginStore {
  // 登录页加载状态
  @observable loading = true;
  // 浏览器地址查询参数
  @observable queryParams = {};
  // 升级状态，状态为0时正常显示登录页，否则跳转升级页面
  @observable updatestatus = '';
  // CAS状态，状态为0时正常显示登录页，否则跳转登录后页面
  @observable casstatus = '';
  // 多语言
  @observable multiLangs = getLSValue('login', 'multiLangs') || [];
  // 动态密码有效时间
  @observable dynamicPasswordTime = 0;
  @observable dynamicPasswordInterval = 0;
  // 登录验证码刷新参数
  @observable seriesnum_ = 0;
  // 二维码有效时间
  @observable qrcodeValidTime = 30;
  @observable qrcodeReqTime = 1;
  // 二维码是否已失效
  @observable qrcodeIsInvalid = false;
  // 移动客户端下载地址
  @observable emobileDownloadUrl = '';
  // 登录页状态
  @observable state = Object.assign(
    {},
    {
      win_width: jQuery(window).width(),
      win_height: jQuery(window).height(),
      isLogging: false,
      hasMultiLang: false,
      multiLangVisible: false,
      loginFormItems: [],
      loginFormHiddenItems: [],
      loginSetting: {},
      qrCode: {},
      validateCode: '/weaver/weaver.file.MakeValidateCode?seriesnum_=0',
      labelInfo: [],
    },
    Object.assign({}, getLSValue('login', 'loginCache'), {
      loginType: getLSValue('login', 'loginType') || 'form',
      langId: getLSValue('login', 'langId') || '',
      langText: getLSValue('login', 'langText') || '',
      isRememberAccount: getLSValue('login', 'isRememberAccount') || getCookieValue('isRememberAccount') || false,
      isRememberPassword: getLSValue('login', 'isRememberPassword') || getCookieValue('isRememberPassword') || false,
      cacheAccount: getLSValue('login', 'cacheAccount') || getCookieValue('cacheAccount') || '',
      cachePassword: getLSValue('login', 'cachePassword') || getCookieValue('cachePassword') || '',
      initialSlide: getLSValue('login', 'initialSlide') || 0,
      autoCarousel: getLSValue('login', 'autoCarousel') || false,
      carouselTime: getLSValue('login', 'carouselTime') || 3,
    }),
  );
  // 登录表单数据加载状态
  @observable loginFormDataLoading = false;
  // 自定义登录组件加载状态
  @observable customloading = false;
  // 登录页事件加载状态
  @observable beforLoginRenderEventStatus = false;
  @observable afterLoginRenderEventStatus = false;

  constructor() {
    this.onWindowResize = this.onWindowResize.bind(this);
    this.setQueryParams = this.setQueryParams.bind(this);
    this.setState = this.setState.bind(this);
    this.setStateAndCache = this.setStateAndCache.bind(this);
    this.getMultiLangs = this.getMultiLangs.bind(this);
    this.getUpgradeInfo = this.getUpgradeInfo.bind(this);
    this.getLoginInfo = this.getLoginInfo.bind(this);
    this.getLoginForm = this.getLoginForm.bind(this);
    this.getElementStyle = this.getElementStyle.bind(this);
    this.onPasswordForget = this.onPasswordForget.bind(this);
    this.onRememberChange = this.onRememberChange.bind(this);
    this.onBgImageChange = this.onBgImageChange.bind(this);
    this.onValidateCodeChange = this.onValidateCodeChange.bind(this);

    jQuery(window).resize(() => this.onWindowResize());
  }

  @computed
  get labelObj() {
    const { langId, labelInfo, loginTemplateTitle, loginTemplateTitle_base64 } = this.state;
    if (loginTemplateTitle_base64) {
        document.title = getCurrentLabel(getMultiStrFromBase64(loginTemplateTitle_base64), langId) || loginTemplateTitle;
    } else {
        document.title = loginTemplateTitle;
    }
    return labelInfo[`langid${langId}`] || {};
  }

  setTitle = () => {
      const { langId, loginTemplateTitle, loginTemplateTitle_base64 } = this.state;
      if (loginTemplateTitle_base64) {
          document.title = getCurrentLabel(getMultiStrFromBase64(loginTemplateTitle_base64), langId) || loginTemplateTitle;
      } else {
          document.title = loginTemplateTitle;
      }
  }

  @action
  onWindowResize() {
    const width = jQuery(window).width();
    const height = jQuery(window).height();

    if (width < 800) {
      jQuery('#LoginContainer').css({ overflowX: 'scroll' });
    } else {
      jQuery('#LoginContainer').css({ overflowX: 'hidden' });
    }

    if (height < 660) {
      jQuery('#LoginContainer').css({ overflowY: 'scroll' });
    } else {
      jQuery('#LoginContainer').css({ overflowY: 'hidden' });
    }

    this.setState({
      win_width: width < 800 ? 800 : width,
      win_height: height < 660 ? 660 : height,
    });
  }

  @action
  getElementStyle(element) {
    const { win_width, win_height, loginType, loginFormItems, templateType } = this.state;
    let { showtype, isAbsolute, width, height, imgWidth, imgbtn, isloginbtn, imgHeight, rate_x, rate_y, level, vertical, levelMargin, verticalMargin } = element;

    if (!width) {
      width = win_width;
    }
    if (!height) {
      height = win_height;
    }
    if (!imgWidth) {
      imgWidth = win_width;
    }
    if (!imgHeight) {
      imgHeight = win_height;
    }
    let style = {};
    if (isAbsolute == 1) {
      if (isloginbtn == false) { // 老数据
        style = {
          left: `${rate_x * 100}%`,
          width: imgWidth,
          height: imgHeight,
        };
      } else {
        style = {
          left: `${rate_x * 100}%`,
          top: `${rate_y * 100}%`,
          width,
          height,
        };
      }
    } else {
      if (imgbtn == true) { // 图片按钮
        let left = 0;
        switch (level) {
          case 'left':
            left = levelMargin;
            break;
          case 'center':
            left = (win_width - imgWidth) / 2 + levelMargin;
            break;
          case 'right':
            left = win_width - imgWidth - levelMargin;
            break;
        }

        let top = 0;
        switch (vertical) {
          case 'top':
            top = verticalMargin;
            break;
          case 'middle':
            top = (win_height - imgHeight) / 2 + verticalMargin;
            break;
          case 'bottom':
            top = win_height - imgHeight - verticalMargin;
            break;
        }
        style = { left, top, width, height };
      } else { // 登录按钮
        let left = 0;
        switch (level) {
          case 'left':
            left = levelMargin;
            break;
          case 'center':
            left = (win_width - width) / 2 + levelMargin;
            break;
          case 'right':
            left = win_width - width - levelMargin;
            break;
        }

        let top = 0;
        switch (vertical) {
          case 'top':
            top = verticalMargin;
            break;
          case 'middle':
            top = (win_height - height) / 2 + verticalMargin;
            break;
          case 'bottom':
            top = win_height - height - verticalMargin;
            break;
        }
        style = { left, top, width, height };
      }

      if (loginType == 'form' && (templateType == 'E9' || templateType == 'V' || templateType == 'H' || templateType == 'Ecology8')) {
        const len = loginFormItems.length - 2;
        if (len > 0) {
          if (showtype == 'loginbox') {
            style.height += len * 65;
            style.top -= len * 32.5;
          }
          if (showtype == 'logo' || showtype == 'loginForm' || showtype == 'qrcode' || showtype == 'loginButton') {
            style.top -= len * 32.5;
          }
        }
      }
    }
    return style;
  }

  @action
  setQueryParams(params = {}) {
    this.queryParams = params;
    window.queryParams = params;
  }

  @action
  setState(state) {
    this.state = Object.assign({}, this.state, state);

    if (state.langId && state.langText) {
      setLSValue('login', 'langId', state.langId);
      setLSValue('login', 'langText', state.langText);
      WeaTools.ls.set('languageidweaver', state.langId);
    }
  }

  @action
  setStateAndCache(key, value) {
    this.setState({ [key]: value });
    setLSValue('login', key, value);
  }

  @action
  getMultiLangs(params = {}) {
    LOGIN_API.getActiveLanguage(params).then((result) => {
      if (result.status == '1') {
        const { activeLanguageInfo, activeLanguageIds, languageIdentify, systemDefaultLang = {} } = result;

        this.multiLangs = activeLanguageInfo;

        setLSValue('login', 'multiLangs', activeLanguageInfo);
        WeaTools.ls.set('activeLanguageIds', activeLanguageIds);
        WeaTools.ls.set('languageIdentify', languageIdentify);

        // 当前状态中没有语言时，取默认语言
        if (!this.state.langId) {
          let language = {};
          for (let key in systemDefaultLang) {
            language = { id: key, language: systemDefaultLang[key] };
          }
          const { id: langId = '7', language: langText = '简体中文' } = language;
          this.setState({ langId, langText });
          this.getLoginForm({ langId });
        }
      }
      this.setTitle();
    });
  }

  @action
  getUpgradeInfo(params = {}) {
    LOGIN_API.getUpgradeInfo(params).then((result) => {
      const { updatestatus, upgradeurl } = result;
      this.updatestatus = updatestatus;

      if (updatestatus == '0') {
        if (/E-Mobile/i.test(window.navigator.userAgent)) {
          let paramstr = '';
          Object.keys(params).map((key) => {
            paramstr += `&${key}=${params[key]}`;
          });
          if (paramstr != '') paramstr = paramstr.substring(1);
          if (params.service) {
            window.location.href = `/spa/portal/static4mobilelogin/index.html?service=${params.service}#/login?${paramstr}`;
          } else {
            window.location.href = `/spa/portal/static4mobilelogin/index.html#/login?${paramstr}`;
          }
        } else {
          this.doBeforLoginRenderEvent();

          // 检查是否部署了CAS
          LOGIN_API.checkCasIsDeployed().then((result) => {
            const { hasSession } = result;
            // 用户已登录，则直接跳转登录后页面
            if (hasSession && !params.preview && !params.templateType) {
              doEvent('afterLogin', () => window.location.href = '/wui/index.html?#/main');
            } else {
              this.getLoginInfo(params);
            }
          });
        }
      } else if (upgradeurl) {
        window.location.href = upgradeurl;
      }
    });
  }

  @action
  getLoginInfo(params = {}, callBack) {
    this.updatestatus = '0';
    this.casstatus = '0';

    // 获取多语言
    this.getMultiLangs(params);

    this.loading = true;
    LOGIN_API.getLoginInfo(params).then((result) => {
      // 缓存登录日期
      const date = new Date();
      const loginDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      WeaTools.ls.set('loginDate', loginDate);

      if (result.status != '2') {
        const {
          settingversion,
          id: templateId,
          templateType,
          loginSettingInfo = {},
          bgImagesInfo = [],
          layoutData = {},
          isRememberAccount,
          isRememberPassword,
          cacheAccount = '',
          cachePassword = '',
          emobileDownloadUrl,
        } = result;
        const { loginInfo = {} } = loginSettingInfo;
        const { showQrcode, qrcodeValidTime = 30, qrcodeReqTime = 1, defaultQrcode, onlyQrcode } = loginInfo;

        // 判断接口返回的设置版本和缓存的设置版本是否一致
        const _settingversion = getLSValue('login', 'settingversion');
        const _templateId = getLSValue('login', 'templateId');
        const isNewVersion = settingversion != _settingversion || templateId != _templateId;

        // 设置移动客户端下载地址
        this.emobileDownloadUrl = emobileDownloadUrl;

        // 获取登录方式
        this.qrcodeValidTime = qrcodeValidTime;
        this.qrcodeReqTime = qrcodeReqTime;
        let loginType = 'form';
        if (showQrcode) {
          if (onlyQrcode) {
            loginType = 'QRCode';
          } else {
            const _loginType = getLSValue('login', 'loginType') || '';
            loginType = _loginType || (defaultQrcode ? 'QRCode' : 'form');
          }
        }
        setLSValue('login', 'loginType', loginType);
        // 获取幻灯片默认位置
        const _loginBgImage = !isNewVersion ? getLSValue('login', 'loginBgImage') : '';
        let initialSlide = 0;
        const loginBgImage = _loginBgImage || loginInfo.imgsrc;
        for (let i = 0, len = bgImagesInfo.length; i < len; i++) {
          if (bgImagesInfo[i].imgsrc == loginBgImage) {
            initialSlide = i;
            break;
          }
        }
        setLSValue('login', 'initialSlide', initialSlide);
        // 获取幻灯片是否自动轮播
        const _autoCarousel = !isNewVersion ? getLSValue('login', 'autoCarousel') : undefined;
        const autoCarousel = _autoCarousel != undefined ? _autoCarousel : loginInfo.autoCarousel;
        setLSValue('login', 'autoCarousel', autoCarousel);
        // 获取幻灯片自动轮播间隔时间
        const _carouselTime = !isNewVersion ? getLSValue('login', 'carouselTime') : '';
        const carouselTime = _carouselTime || loginInfo.carouselTime;
        setLSValue('login', 'carouselTime', carouselTime);

        // 获取记住的账号和密码
        if (isRememberAccount != undefined) {
          setLSValue('login', 'isRememberAccount', isRememberAccount);
          setLSValue('login', 'isRememberPassword', isRememberPassword);
          setLSValue('login', 'cacheAccount', cacheAccount);
          setLSValue('login', 'cachePassword', cachePassword);

          this.setState({ isRememberAccount, isRememberPassword, cacheAccount, cachePassword });
        }

        const state = Object.assign({}, result, { loginType, initialSlide, autoCarousel, carouselTime });
        setLSValue('login', 'loginCache', state);

        if (isNewVersion || templateType == 'ECustom') {
          setLSValue('login', 'settingversion', settingversion);
          setLSValue('login', 'templateId', templateId);
          setLSValue('login', 'templateType', templateType);
          setLSValue('login', 'loginBgImage', loginInfo.imgsrc);
          setLSValue('login', 'loginBgImageWidth', loginInfo.width);
          setLSValue('login', 'loginBgImageHeight', loginInfo.height);

          this.setState(state);

          if (templateType == 'ECustom') {
            this.onLoadECustomLogin(layoutData);
          }
        }
        this.setTitle();
      } else {
        message.error(result.errormsg);
      }
      if (callBack) {
        callBack();
      }
      this.loading = false;
    });
  }

  @action
  onLoadECustomLogin(layoutData = {}) {
    const { layoutCustom, layoutConfig } = layoutData;
    const success = () => {
      const _interval = window.setInterval(() => {
        if (window.weaPortalPublic) {
            this.customloading = true;
            window.clearInterval(_interval);
        }
      }, 100);
    };
    if (layoutCustom == '1' && layoutConfig && layoutConfig.id) {
      WeaTools.loadDevModules(layoutConfig.id, layoutConfig.module).then(() => {
        const _interval = window.setInterval(() => {
          if (window[layoutConfig.module]) {
            this.customloading = true;
            window.clearInterval(_interval);
          }
        }, 100);
      });
    } else {
      const files = [...ecComFiles, ...comMobxFiles, ...portalPublicFiles];
      loadjs.isDefined('portalPublic') ? loadjs.ready('portalPublic', success) : loadjs(files, 'portalPublic', {
        async: false,
        success,
      });
    }
  }

  @action
  getLoginForm(params = {}, callback) {
    const queryParams = this.queryParams;
    const { logintype = '1' } = queryParams;
    const { loginId = '', langId = this.state.langId } = params;

    if (langId) {
      window.doLoginAction &&
        window.doLoginAction('getLoginForm', {
          queryParams,
          logintype,
          loginid: loginId,
          langid: langId,
          callback: (result) => {
            const {
              hasMultiLang = false,
              loginFormItems = [],
              loginFormHiddenItems = [],
              loginSetting = {},
              qrCode = {},
            } = result;

            this.setState({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting, qrCode });

            if (callback && typeof callback == 'function') {
              callback();
            }

            // 登录表单数据加载完成
            this.loginFormDataLoading = true;
          },
        });
    }
  }

  @action
  getDynamicPassword() {
    const queryParams = this.queryParams;
    const { logintype = '1' } = queryParams;
    const { langId, loginSetting } = this.state;

    window.doLoginAction &&
      window.doLoginAction('getDynamicPassword', {
        queryParams,
        logintype,
        langid: langId,
        loginSetting,
        success: (params) => {
          const { validitySec = 60 } = params;
          this.dynamicPasswordTime = validitySec;

          const _interval = setInterval(() => {
            const time = this.dynamicPasswordTime;
            if (time == 1) {
              window.clearInterval(this.dynamicPasswordInterval);
            }
            this.dynamicPasswordTime = time - 1;
          }, 1000);
          this.dynamicPasswordInterval = _interval;
        },
      });
  }

  @action
  onBgImageChange(params, index) {
    const { imgsrc, width, height } = params;
    const loginInfo = Object.assign({}, this.state.loginSettingInfo.loginInfo, { imgsrc, width, height });
    const loginSettingInfo = Object.assign({}, this.state.loginSettingInfo, { loginInfo });
    this.setState({ loginSettingInfo, initialSlide: index });

    setLSValue('login', 'initialSlide', index);
    setLSValue('login', 'loginBgImage', imgsrc);
    setLSValue('login', 'loginBgImageWidth', width);
    setLSValue('login', 'loginBgImageHeight', height);
  }

  @action
  onRememberChange(type, checked) {
    const { isRememberAccount, isRememberPassword } = this.state;
    if (type == 'account') {
      this.setState({
        isRememberAccount: checked,
        isRememberPassword: !checked ? checked : isRememberPassword,
      });
    } else if (type == 'password') {
      this.setState({
        isRememberAccount: checked || isRememberAccount,
        isRememberPassword: checked,
      });
    }
  }

  @action
  onPasswordForget(params = {}) {
    const { langId = this.state.langId } = params;
    window.doLoginAction && window.doLoginAction('forgetPassword', { langid: langId });
  }

  @action
  onValidateCodeChange() {
    setTimeout(
      () =>
        this.setState({
          validateCode: `/weaver/weaver.file.MakeValidateCode?seriesnum_=${++this.seriesnum_}`,
        }),
      50,
    );
  }

  @action
  onLogin() {
    const queryParams = this.queryParams;
    const { logintype = '1', gopage = '', target = '1' } = queryParams;
    const { langId, langText, isRememberAccount, isRememberPassword, loginSetting, loginSettingInfo = {} } = this.state;
    const { loginInfo = {} } = loginSettingInfo;
    const { isOpenGopage = true } = loginInfo;

    this.setState({ isLogging: true });
    doEvent('beforLogin', () => {
      window.doLoginAction &&
        window.doLoginAction('login', {
          queryParams,
          logintype,
          langid: langId,
          loginSetting,
          isRememberAccount,
          isRememberPassword,
          success: (username, password, params = {}) => {
            jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();

            let cacheAccount = '';
            let cachePassword = '';
            if (isRememberAccount) cacheAccount = username;
            if (isRememberPassword) cachePassword = password;
            this.setState({ isRememberAccount, isRememberPassword, cacheAccount, cachePassword });

            initLSValue(username, langId);
            setLSValue('login', 'loginId', username);
            setLSValue('login', 'cacheAccount', cacheAccount);
            setLSValue('login', 'cachePassword', cachePassword);
            setLSValue('login', 'isRememberAccount', isRememberAccount);
            setLSValue('login', 'isRememberPassword', isRememberPassword);

            // 直接跳转到后端
            if (params.needJumpToBackstage) {
              window.top.location.href = '/wui/engine.html';
              return;
            }

            doEvent('afterLogin', () => {
              // 登录后跳转超时前页面
              const ls_gopage = WeaTools.ls.getStr('gopage');
              WeaTools.ls.set('gopage', '');

              if (ls_gopage && isOpenGopage) {
                window.top.location.href = decodeURIComponent(ls_gopage);
              } else {
                // 登录成功回调
                let { needJump = true } = params;
                if (window.onLoginCallback && typeof window.onLoginCallback == 'function') {
                  needJump = window.onLoginCallback(params);
                }

                // 登录成功回调返回true时，继续标准跳转
                if (needJump) {
                  if (logintype == '2') {
                    window.top.location.href = '/spa/crmPortal/mobx/index.html#/main';
                  } else {
                    // 判断当前登录日期和上次登录的日期是否为同一天，不是同一天则强制刷新页面
                    const date = new Date();
                    const loginDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
                    const _loginDate = WeaTools.ls.getStr('loginDate');

                    if (window.top.location.pathname != '/wui/index.html') {
                      window.top.location.href = '/wui/index.html#/main';
                    } else if (loginDate != _loginDate) {
                      WeaTools.ls.set('loginDate', loginDate);

                      let href = '/wui/index.html?#/main';
                      if (gopage) {
                        href += `?gopage=${encodeURIComponent(gopage)}&target=${target}`;
                      }
                      window.top.location.href = href;
                    } else {
                      this.beforLoginRenderEventStatus = false;
                      this.afterLoginRenderEventStatus = false;

                      let pathname = '/main';
                      if (gopage) {
                        pathname += `?gopage=${encodeURIComponent(gopage)}&target=${target}`;
                      }
                      window.top.weaHistory.push({ pathname });
                    }
                  }
                }
              }

              window.clearInterval(this.dynamicPasswordInterval);
              this.dynamicPasswordTime = 0;

              this.setState({ isLogging: false });
            });
          },
          failure: (params = {}) => {
            if (params.reflashValidateCode) {
              this.onValidateCodeChange();
            }
            this.getLoginForm();
            this.setState({ isLogging: false });
          },
        });
    });
  }

  // 扫码登录
  @action
  onQCLogin() {
    // 二维码已失效
    if (this.qrcodeIsInvalid) return;

    const queryParams = this.queryParams;
    const { gopage = '', target = '1' } = queryParams;
    const { langId, langText, qrCode, loginSettingInfo = {} } = this.state;
    const { loginInfo = {} } = loginSettingInfo;
    const { isOpenGopage = true } = loginInfo;

    LOGIN_API.login4qc({
      langid: langId,
      loginkey: qrCode.loginkey,
      isie: ua.browser === 'IE',
      ...queryParams,
    }).then((result) => {
      if (result.status == '1') {
        jQuery.setSessionTimeZone && jQuery.setSessionTimeZone();
        
        // 处理sso扫码登录
        if (queryParams && queryParams.appid && queryParams.service) {
            queryParams.authenticationType = 2;
            jQuery('body').append("<form name='ssoForm'></form>");
            let form = jQuery("form[name='ssoForm']");
            form.attr('action', '/login/VerifyLoginWeaversso.jsp');
            form.attr('method', 'post');
            form.attr('style', 'display:none');
            for (let key in queryParams) {
                form.append(`<input type='text' name='${key}' value = '${queryParams[key]}'></input>`);
            }
            // 跳转到sso
            form.submit();
            return;
        }

        // 直接跳转到后端
        if (result.needJumpToBackstage) {
          window.top.location.href = '/wui/engine.html';
          return;
        }

        doEvent('afterLogin', () => {
          // 登录后跳转超时前页面
          const ls_gopage = WeaTools.ls.getStr('gopage');
          WeaTools.ls.set('gopage', '');

          if (ls_gopage && isOpenGopage) {
            window.top.location.href = decodeURIComponent(ls_gopage);
          } else if (window.top.location.pathname != '/wui/index.html') {
              window.top.location.href = '/wui/index.html#/main';
            } else {
              this.beforLoginRenderEventStatus = false;
              this.afterLoginRenderEventStatus = false;

              let pathname = '/main';
              if (gopage) {
                pathname += `?gopage=${encodeURIComponent(gopage)}&target=${target}`;
              }
              window.top.weaHistory.push({ pathname });
            }
        });
      }
    });
  }

  @action
  onQCLoginStart(cusQrcodeValidTime, cusQrcodeReqTime) {
    this.qrcodeIsInvalid = false; // 二维码生效

    const qrcodeValidTime = cusQrcodeValidTime || this.qrcodeValidTime;
    const qrcodeReqTime = cusQrcodeReqTime || this.qrcodeReqTime;

    let qrcodeUsedTime = 1;
    this.qrcodeCdInterval = window.setInterval(() => {
      if (qrcodeUsedTime >= qrcodeValidTime) {
        this.onQCLoginEnd();
      }
      qrcodeUsedTime++;
    }, 1000);

    this.qrcodeLoginInterval = window.setInterval(() => this.onQCLogin(), qrcodeReqTime * 1000);
  }

  @action
  onQCLoginEnd() {
    this.qrcodeIsInvalid = true; // 二维码失效
    window.clearInterval(this.qrcodeCdInterval);
    window.clearInterval(this.qrcodeLoginInterval);
  }

  // 执行登录页加载前事件
  @action
  doBeforLoginRenderEvent() {
    // 防止重复执行
    if (!this.beforLoginRenderEventStatus) {
      doEvent('beforLoginRender', () => (this.beforLoginRenderEventStatus = true));
    }
  }

  // 执行登录页加载后事件
  @action
  doAfterLoginRenderEvent() {
    // 防止重复执行
    if (!this.afterLoginRenderEventStatus) {
      doEvent('afterLoginRender', () => (this.afterLoginRenderEventStatus = true));
    }
  }
}
